package com.hspedu.hspspringmvc.servlet;

import com.hspedu.hspspringmvc.annotation.Controller;
import com.hspedu.hspspringmvc.annotation.RequestMapping;
import com.hspedu.hspspringmvc.annotation.RequestParam;
import com.hspedu.hspspringmvc.context.HspWebApplicationContext;
import com.hspedu.hspspringmvc.handler.HspHandler;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HspDispatcherServlet extends HttpServlet {

    private HspWebApplicationContext hspWebApplicationContext;


    //存放 url 和 控制器-方法的映射关系
    private ArrayList<HspHandler> handlerList =
            new ArrayList<>();


    @Override
    public void init(ServletConfig config) throws ServletException {
        String contextConfigLocation =
                config.getInitParameter("contextConfigLocation");
        hspWebApplicationContext = new HspWebApplicationContext(contextConfigLocation);
        hspWebApplicationContext.init();
        initHandlerMapping();
        System.out.println("handlerList：" + handlerList);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
        System.out.println("HspDispatcherServlet doGet()被调用");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        executeDispatch(req, resp);
        System.out.println("HspDispatcherServlet doPost()被调用");
    }

    public void initHandlerMapping() {

        if (hspWebApplicationContext.ioc.isEmpty()) {
            return;
        }

        for (Map.Entry<String, Object> entry : hspWebApplicationContext.ioc.entrySet()) {
            Class<?> aClass = entry.getValue().getClass();
            if (aClass.isAnnotationPresent(Controller.class)) {
                Method[] declaredMethods = aClass.getDeclaredMethods();
                for (Method method : declaredMethods) {
                    if (method.isAnnotationPresent(RequestMapping.class)) {
                        RequestMapping annotation = method.getAnnotation(RequestMapping.class);
                        String url = annotation.value();
                        HspHandler hspHandler = new HspHandler(url, entry.getValue(), method);
                        handlerList.add(hspHandler);

                    }

                }

            }

        }

    }

    public HspHandler getHspHandler(HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        for (HspHandler hspHandler : handlerList) {
            if (requestURI.equals(hspHandler.getUrl())) {
                return hspHandler;
            }
        }
        return null;

    }

    public void executeDispatch(HttpServletRequest request, HttpServletResponse response) {
        HspHandler hspHandler = getHspHandler(request);
        try {
            if (null == hspHandler) {
                response.getWriter().print("<h1>404 NOT FOUND</h1>");
            } else {
                //通过反射得到的参数数组-> 在反射调用方法时会使用到
                //getParameterTypes 或得到当前这个方法的所有参数信息
                Class<?>[] parameterTypes = hspHandler.getMethod().getParameterTypes();

                Object[] params = new Object[parameterTypes.length];

                for (int i = 0; i < parameterTypes.length; i++) {
                    Class<?> parameterType = parameterTypes[i];
                    if (parameterType.getSimpleName().equals("HttpServletRequest")) {
                        params[i] = request;
                    } else if (parameterType.getSimpleName().equals("HttpServletResponse")) {
                        params[i] = response;
                    }
                }
                Map<String, String[]> parameterMap = request.getParameterMap();
                for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                    String name = entry.getKey();
                    String values = entry.getValue()[0];
                    int indexRequestParamIndex = getIndexRequestParamIndex(hspHandler.getMethod(), name);
                    if (indexRequestParamIndex != -1) {
                        params[indexRequestParamIndex] = values;
                    }else {
                        getParameterNames(hspHandler.getMethod());
                    }


                }


                hspHandler.getMethod().invoke(hspHandler.getController(), params);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    private int getIndexRequestParamIndex(Method method, String name) {

        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            Parameter parameter = parameters[i];
            boolean annotationPresent = parameter.isAnnotationPresent(RequestParam.class);
            if (annotationPresent) {
                RequestParam annotation = parameter.getAnnotation(RequestParam.class);
                String value = annotation.value();
                if (value.equals(name)) {
                    return i;
                }
            }
        }
        return -1;
    }

    public List<String> getParameterNames(Method method){
        Parameter[] parameters = method.getParameters();
        List<String> parameterNames = new ArrayList<>();
        for (Parameter parameter : parameters){
            String name = parameter.getName();
            parameterNames.add(name);


        }
        System.out.println(parameterNames);
        return parameterNames;
    }
}
